package com.huynhchihieu.dao;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;


//@Repository // cho nay co can dung no la 1 bean ko?
public class GenericDAOImpl<T> implements GenericDAO<T> {

	@PersistenceContext(name = "persistenceUnit")
	EntityManager entityManager;

	public T create(T t) {
		entityManager.persist(t);
		entityManager.flush();
		entityManager.refresh(t);
		return t;
	}

	public T find(Class<T> type, Object id) {

		return entityManager.find(type, id);
	}

	public T update(T t) {
		return entityManager.merge(t);
	}

	public void delete(Class<T> type, Object id) {
		Object ref = entityManager.getReference(type, id);
		entityManager.remove(ref);
	}

	public List findWithNamedQuery(String queryName) {
		// TODO Auto-generated method stub
		return entityManager.createNamedQuery(queryName).getResultList();
	}

	public List findWithNamedQuery(String queryName, int resultLimit) {

		return entityManager.createNativeQuery(queryName).setMaxResults(resultLimit).getResultList();
	}

	public List findWithNamedQuery(String namedQueryName, Map parameters) {
		
		return findWithNamedQuery( namedQueryName,  parameters, 0);
	}

	public List findWithNamedQuery(String namedQueryName, Map parameters, int resultLimit) {
		//Set rawParameters = parameters.entrySet();
		Set<Entry<Object, Object>> rawParameters = parameters.entrySet();
		Query query = entityManager.createNamedQuery(namedQueryName);
		if (resultLimit > 0)
			query.setMaxResults(resultLimit);
		for (Entry entry : rawParameters) {
			query.setParameter((String) entry.getKey(), entry.getValue());
		}
		return query.getResultList();
	}

}
